<template>
	<view class="modern-container">
		<view class="header">
			<text class="title">预约管理</text>
			<text class="subtitle">按老师分类查看所有辅导预约</text>
		</view>

		<view class="teacher-container">
			<view class="teacher-card" v-for="teacher in teachers" :key="teacher.teacherId">
				<view class="teacher-header" @click="toggleAppointments(teacher.teacherId)">
					<image class="teacher-avatar" :src="teacher.avatarUrl" mode="aspectFill"></image>
					<view class="teacher-info">
						<text class="teacher-name">{{ teacher.teacherName }}</text>
						<text class="teacher-meta">{{ teacher.appointments.length }}个预约 ·
							{{ teacher.teacherPhone }}</text>
					</view>
					<uni-icons :type="expandedTeachers[teacher.teacherId] ? 'arrowup' : 'arrowdown'" size="20"
						color="#666"></uni-icons>
				</view>

				<transition name="slide-fade">
					<view v-show="expandedTeachers[teacher.teacherId]" class="teacher-content">
						<view class="search-container">
							<uni-icons type="search" size="18" color="#999" class="search-icon"></uni-icons>
							<input class="search-input" placeholder="搜索学生姓名..." v-model="teacher.searchKeyword"
								@input="handleSearchInput(teacher)" @focus="handleSearchFocus(teacher)"
								@blur="handleSearchBlur(teacher)" confirm-type="search" />
						</view>

						<view class="appointment-list">
							<view class="appointment-card" v-for="(appointment, index) in teacher.filteredAppointments"
								:key="appointment.id" :style="{animationDelay: `${index * 0.05}s`}">
								<view class="appointment-header">
									<view class="appointment-index">#{{ index + 1 }}</view>
									<view class="appointment-status"
										:style="{backgroundColor: getStatusColor(appointment.isFinish)}">
										{{ getStatusText(appointment.isFinish) }}
									</view>
								</view>

								<view class="appointment-body">
									<view class="info-row">
										<uni-icons type="person" size="16" color="#5a7dff"></uni-icons>
										<text class="info-text">{{ appointment.studentName }}
											({{ appointment.studentGrade }})</text>
									</view>
									<view class="info-row">
										<uni-icons type="phone" size="16" color="#5a7dff"></uni-icons>
										<text class="info-text">{{ appointment.studentPhone }}</text>
									</view>
									<view class="info-row">
										<uni-icons type="calendar" size="16" color="#5a7dff"></uni-icons>
										<text
											class="info-text">{{ formatAppointmentTime(appointment.appointmentTime) }}</text>
									</view>
									<view class="info-row">
										<uni-icons type="chat" size="16" color="#5a7dff"></uni-icons>
										<text class="info-text">{{ appointment.appointmentContent }}</text>
									</view>
									<view class="info-row">
										<uni-icons type="flag" size="16"
											:color="getStatusColor(appointment.isFinish)"></uni-icons>
										<text class="info-text" :style="{color: getStatusColor(appointment.isFinish)}">
											{{ getStatusText(appointment.isFinish) }}
										</text>
									</view>

									<view class="evaluation" v-if="appointment.teacherComponent">
										<uni-icons type="compose" size="16" color="#5a7dff"></uni-icons>
										<text class="info-text">{{ appointment.teacherComponent }}</text>
									</view>
									<view class="evaluation" v-if="appointment.component">
										<uni-icons type="feedback" size="16" color="#5a7dff"></uni-icons>
										<text class="info-text">{{ appointment.component }}</text>
									</view>
								</view>

								<view class="appointment-actions">
									<button class="action-btn edit-btn" @click.stop="editAppointment(appointment)">
										<uni-icons type="compose" size="16" color="#fff"></uni-icons>
										<text>编辑</text>
									</button>
									<button class="action-btn delete-btn" @click.stop="deleteAppointment(appointment)">
										<uni-icons type="trash" size="16" color="#fff"></uni-icons>
										<text>删除</text>
									</button>
								</view>
							</view>
						</view>

						<view class="no-results"
							v-if="teacher.filteredAppointments.length === 0 && teacher.searchKeyword">
							<image src="/static/no-data.png" class="no-data-img"></image>
							<text class="no-data-text">没有找到匹配的学生</text>
						</view>
					</view>
				</transition>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';
	export default {
		data() {
			return {
				appointments: [],
				expandedTeachers: {},
				searchTimer: null
			};
		},
		onShow() {
			this.loadAppointments();
		},
		computed: {
			teachers() {
				const teacherMap = {};
				this.appointments.forEach((appointment) => {
					if (!teacherMap[appointment.teacherId]) {
						teacherMap[appointment.teacherId] = {
							teacherName: appointment.teacherName,
							teacherId: appointment.teacherId,
							teacherPhone: appointment.teacherPhone,
							avatarUrl: this.getTeacherAvatarUrl(appointment.teacherPhone),
							appointments: [],
							searchKeyword: '',
							filteredAppointments: []
						};
					}
					teacherMap[appointment.teacherId].appointments.push(appointment);
				});

				// 对每个老师的appointments进行排序
				Object.values(teacherMap).forEach((teacher) => {
					teacher.appointments.sort((a, b) => {
						// 按时间降序排列
						const dateA = a.appointmentTime.split(' ')[0];
						const dateB = b.appointmentTime.split(' ')[0];
						return new Date(dateB) - new Date(dateA);
					});
					// 初始化筛选结果
					teacher.filteredAppointments = [...teacher.appointments];
				});
				return Object.values(teacherMap);
			},
		},
		methods: {
			loadAppointments() {
				let that = this;
				uni.showLoading({
					title: '加载中...'
				});
				uni.request({
					url: globalVariable + "/getAllAppointmentAdmin",
					success(res) {
						uni.hideLoading();
						let info = res.data;
						that.appointments = info.data;
					},
					fail() {
						uni.hideLoading();
						uni.showToast({
							title: '加载失败',
							icon: 'none'
						});
					}
				});
			},
			getTeacherAvatarUrl(teacherPhone) {
				return `${globalVariable}/get/${teacherPhone}.png` || '/static/default-teacher.png';
			},
			getStatusText(status) {
				return status === 2 ? '已完成' : status === 1 ? '已辅导待确认' : "未辅导";
			},
			getStatusColor(status) {
				return status === 2 ? '#4CAF50' : status === 1 ? '#FF9800' : "#F44336";
			},
			toggleAppointments(teacherId) {
				this.$set(this.expandedTeachers, teacherId, !this.expandedTeachers[teacherId]);
				// 展开时重置搜索状态
				if (this.expandedTeachers[teacherId]) {
					const teacher = this.teachers.find(t => t.teacherId === teacherId);
					if (teacher) {
						teacher.searchKeyword = '';
						teacher.filteredAppointments = [...teacher.appointments];
					}
				}
			},
			handleSearchInput(teacher) {
				// 防抖处理，避免频繁触发
				if (this.searchTimer) {
					clearTimeout(this.searchTimer);
				}
				this.filterAppointments(teacher);
				this.searchTimer = setTimeout(() => {

				}, 300);
			},
			handleSearchFocus(teacher) {
				// 可以添加一些视觉反馈
				console.log('搜索框获取焦点', teacher.teacherName);
			},
			handleSearchBlur(teacher) {
				// 可以添加一些视觉反馈
				console.log('搜索框失去焦点', teacher.teacherName);
			},
			filterAppointments(teacher) {
				// 确保使用原始数据而不是代理对象
				const originalAppointments = [...teacher.appointments];

				// 获取搜索关键词并处理
				const keyword = (teacher.searchKeyword || '').trim().toLowerCase();

				// 使用计算属性确保响应式更新
				this.$set(teacher, 'filteredAppointments',
					originalAppointments.filter(appointment => {
						const studentName = (appointment.studentName || '').toLowerCase();
						return studentName.includes(keyword);
					})
				);
			},

			handleSearchInput(teacher) {
				// 使用防抖优化性能
				clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					this.filterAppointments(teacher);
				}, 300);
			},
			formatAppointmentTime(timeStr) {
				if (!timeStr) return '';
				// 格式化显示时间
				const [date, time, duration] = timeStr.split(' ');
				return `${date} ${time} (${duration}分钟)`;
			},
			editAppointment(appointment) {
				let appointmentStr = JSON.stringify(appointment);
				uni.navigateTo({
					url: "/pages/AppointmentEdit/AppointmentEdit?appointment=" + appointmentStr
				});
			},
			deleteAppointment(appointment) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个预约吗？此操作不可恢复。',
					cancelText: "取消",
					confirmText: "删除",
					confirmColor: '#F44336',
					success: (res) => {
						if (res.confirm) {
							let id = appointment.id;
							uni.showLoading({
								title: '删除中...'
							});
							uni.request({
								url: globalVariable + "/deleteAppointmentById?id=" + id,
								method: 'POST',
								success: (res) => {
									uni.hideLoading();
									let info = res.data;
									uni.showToast({
										title: info.message,
										icon: info.status === 1 ? 'success' : 'none'
									});
									if (info.status === 1) {
										setTimeout(() => {
											this.loadAppointments();
										}, 1500);
									}
								},
								fail: () => {
									uni.hideLoading();
									uni.showToast({
										title: '删除失败',
										icon: 'none'
									});
								}
							});
						}
					}
				});
			}
		},
	};
</script>

<style scoped>
	.modern-container {
		padding: 24rpx;
		background-color: #f5f7fa;
		min-height: 100vh;
		padding-bottom: 40rpx;
	}

	.header {
		text-align: center;
		margin-bottom: 40rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		display: block;
		margin-bottom: 12rpx;
	}

	.subtitle {
		font-size: 26rpx;
		color: #999;
	}

	.teacher-container {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
	}

	.teacher-card {
		background-color: #fff;
		border-radius: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
		overflow: hidden;
		transition: all 0.3s ease;
	}

	.teacher-card:active {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.teacher-header {
		display: flex;
		align-items: center;
		padding: 32rpx;
		cursor: pointer;
	}

	.teacher-avatar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		margin-right: 24rpx;
		object-fit: cover;
		border: 4rpx solid #f0f5ff;
		box-shadow: 0 4rpx 12rpx rgba(90, 125, 255, 0.1);
	}

	.teacher-info {
		flex: 1;
	}

	.teacher-name {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
		display: block;
		margin-bottom: 8rpx;
	}

	.teacher-meta {
		font-size: 24rpx;
		color: #999;
	}

	.teacher-content {
		padding-bottom: 32rpx;
	}

	.search-container {
		position: relative;
		margin: 0 32rpx 24rpx;
		background-color: #f8f9fa;
		border-radius: 12rpx;
		transition: all 0.3s;
	}

	.search-container:focus-within {
		background-color: #fff;
		box-shadow: 0 0 0 2rpx rgba(90, 125, 255, 0.2);
	}

	.search-icon {
		position: absolute;
		left: 24rpx;
		top: 50%;
		transform: translateY(-50%);
		z-index: 1;
	}

	.search-input {
		width: 100%;
		padding: 20rpx 20rpx 20rpx 60rpx;
		font-size: 28rpx;
		color: #333;
		border: none;
		background: transparent;
	}

	.search-input:focus {
		outline: none;
	}

	.appointment-list {
		padding: 0 32rpx;
	}

	.appointment-card {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		animation: fadeInUp 0.4s ease forwards;
		opacity: 0;
		transform: translateY(20rpx);
	}

	@keyframes fadeInUp {
		from {
			opacity: 0;
			transform: translateY(20rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.appointment-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
		padding-bottom: 16rpx;
		border-bottom: 2rpx solid #f5f5f5;
	}

	.appointment-index {
		font-size: 28rpx;
		font-weight: 600;
		color: #5a7dff;
	}

	.appointment-status {
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
		color: white;
		font-weight: 500;
	}

	.appointment-body {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
		margin-bottom: 24rpx;
	}

	.info-row {
		display: flex;
		align-items: flex-start;
	}

	.info-text {
		font-size: 28rpx;
		color: #666;
		margin-left: 12rpx;
		flex: 1;
		line-height: 1.5;
	}

	.evaluation {
		background-color: #f8faff;
		border-radius: 12rpx;
		padding: 16rpx;
		margin-top: 16rpx;
		display: flex;
	}

	.appointment-actions {
		display: flex;
		justify-content: flex-end;
		gap: 16rpx;
	}

	.action-btn {
		height: 64rpx;
		border-radius: 32rpx;
		padding: 0 32rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border: none;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		transition: all 0.2s;
	}

	.action-btn text {
		margin-left: 8rpx;
	}

	.action-btn:active {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
	}

	.edit-btn {
		background: linear-gradient(135deg, #5a7dff 0%, #7b9aff 100%);
		color: white;
	}

	.delete-btn {
		background: linear-gradient(135deg, #FF5252 0%, #F44336 100%);
		color: white;
	}

	.no-results {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60rpx 0;
	}

	.no-data-img {
		width: 200rpx;
		height: 200rpx;
		opacity: 0.5;
		margin-bottom: 24rpx;
	}

	.no-data-text {
		font-size: 28rpx;
		color: #999;
	}

	.slide-fade-enter-active {
		transition: all 0.3s ease-out;
	}

	.slide-fade-leave-active {
		transition: all 0.2s ease-in;
	}

	.slide-fade-enter-from,
	.slide-fade-leave-to {
		opacity: 0;
		transform: translateY(-20rpx);
	}
</style>